package cn.hamster3.mc.plugin.core.common.api;

import cn.hamster3.mc.plugin.core.common.config.ConfigSection;
import cn.hamster3.mc.plugin.core.common.thread.NamedThreadFactory;
import cn.hamster3.mc.plugin.core.common.util.CoreUtils;
import com.google.gson.Gson;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Getter;
import net.kyori.adventure.platform.AudienceProvider;
import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.JedisPool;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Logger;

@SuppressWarnings("unused")
public abstract class CoreAPI {
    @Getter
    protected static CoreAPI instance;
    /**
     * Redis 连接池
     */
    @Getter
    @NotNull
    private final JedisPool jedisPool;
    /**
     * HamsterCore 公用数据库连接池
     */
    @Getter
    @NotNull
    private final HikariDataSource hikariDataSource;
    /**
     * 异步线程池
     */
    @Getter
    private final ExecutorService executorService;
    /**
     * 调度器线程池
     */
    @Getter
    private final ScheduledExecutorService scheduledService;

    public CoreAPI(@NotNull ConfigSection config) {
        executorService = Executors.newCachedThreadPool(new NamedThreadFactory("HamsterCore - Executor"));
        scheduledService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("HamsterCore - Scheduler"));

        getLogger().info("正在创建 Redis 连接池");
        jedisPool = new JedisPool(config.getString("redis-url"));
        getLogger().info("Redis 连接池创建完成");

        ConfigSection datasourceConfig = config.getSection("datasource");
        if (datasourceConfig == null) {
            throw new IllegalArgumentException("配置文件中未找到 datasource 节点");
        }
        getLogger().info("正在创建数据库连接池");
        hikariDataSource = (HikariDataSource) CoreUtils.getDataSource(datasourceConfig);
        getLogger().info("数据库连接池创建完成");
    }

    /**
     * 获取 HamsterCore 公用数据库连接池
     *
     * @return 公用数据库连接池
     */
    @NotNull
    public DataSource getDataSource() {
        return hikariDataSource;
    }

    /**
     * 获取 HamsterCore 公用数据库连接
     *
     * @return 公用数据库连接
     * @throws SQLException -
     */
    @NotNull
    public Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    @NotNull
    public abstract Logger getLogger();

    /**
     * @return GSON 工具
     */
    @NotNull
    public abstract Gson getGson();

    /**
     * @return GSON 工具，会使用格式化输出、且解析中包含null参数
     */
    @NotNull
    public abstract Gson getGsonHuman();

    @NotNull
    public abstract AudienceProvider getAudienceProvider();
}
